import { defineStore } from 'pinia';
import { storage } from '@/utils/Storage';
import { DOWNLOAD_TASK_MAP } from "@/store/mutation-types";

export type IFileSystemState = {
  downloadMap: Map<string, DownloadType>
};

/** 下载文件的类型数据约束 **/
export interface DownloadType {
  id: string;
  name: string;
  progress: number;
  control: AbortController;
}

export const useFileSystemStore = defineStore({
  id: 'app-filesystem',
  state: (): IFileSystemState => ({
    downloadMap: storage.get(DOWNLOAD_TASK_MAP, new Map())
  }),
  getters: {
    getDownloadMap(): Map<string, DownloadType> {
      return this.downloadMap;
    }
  },
  actions: {
    pushDownloadTask(task: DownloadType): boolean {
      if (this.downloadMap.has(task.id)) {
        return false
      }
      this.downloadMap.set(task.id, task);
      return true
    },
    updateDownloadTask(task: DownloadType) {
      if (this.downloadMap.has(task.id)) {
        const t = this.downloadMap.get(task.id)
        // @ts-ignore
        t.progress = task.progress
      }
    },
    closeDownloadTask(id: string) {
      if (this.downloadMap.has(id)) {
        const task = this.downloadMap.get(id)
        // @ts-ignore
        task.control.abort()
        this.downloadMap.delete(id)
      }
    },
    successDownloadTask(id: string) {
      if (this.downloadMap.has(id)) {
        this.downloadMap.delete(id)
      }
    }
  },
});
